package com.wzh.example.demo;

import com.wzh.example.demo.domain.UserDO;
import com.wzh.example.demo.repository.mapper.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author zh wang
 * @Create 2025/4/14 17:11
 */
@Service
public class DemoService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private DemoService2 demoService2;

    public void updateTable() {
        String sql = "UPDATE test_user SET age = ? WHERE name = ?";
        jdbcTemplate.update(sql, 21, "张三");
    }
    @Transactional
    public void updateTable2() {
        String sql = "UPDATE test_user SET age = ? WHERE name = ?";
        jdbcTemplate.update(sql, 21, "张三");
        //throw new RuntimeException("updateTable2");
    }

    public List<UserDO> getAllUsers() {
        return userRepository.findAll();
    }

    public UserDO getUserByUserName(String userName) {
        return userRepository.findByUserName(userName);
    }

    public UserDO createUser(UserDO userDO) {
        return userRepository.save(userDO);
    }

    /**
     * 测试事务：
     *      测试事务 新开启参数：propagation = Propagation.REQUIRES_NEW
     *      此参数必须是要 spring 去调用
     */
    @Transactional(rollbackFor = Exception.class)
    public void testTransaction() {
        /*
            测试事务：
                1. 方法1 this调用 方法2 ，方法2没有@Transactional，方法2报错，方法1,2都会回滚

         */
        System.out.println("修改 11 开始");
        userRepository.updateEmail("张三", "23");
        System.out.println("修改 11 结束");
        //throw new RuntimeException();
        //testTransaction2();
        //demoService2.testTransaction2();
    }
    //@Transactional(propagation = Propagation.REQUIRES_NEW)
    public void testTransaction2() {
        System.out.println("修改 22 开始");
        userRepository.updateEmail("张三", "222");
        System.out.println("修改 22 结束");
        try {
            throw new Exception("测试事务");
        } catch (Exception e) {
            System.out.println("testTransaction2");
        }
    }
    public void testTransaction3() {
        testTransaction();
    }
    @Transactional
    public void testTransaction41() {
        System.out.println("修改 testTransaction41 开始");
        userRepository.updateEmail("张三", "1");
        System.out.println("修改 testTransaction41 结束");
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void testTransaction42() {
        System.out.println("修改 testTransaction42 开始");
        userRepository.updateEmail("张三", "2");
        System.out.println("修改 testTransaction42 结束");
        throw new RuntimeException("testTransaction42");
    }

}
